package com.example.myapplication;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class JsonParse {
    private static JsonParse instance;
    private JsonParse(){}
    public static JsonParse getInstance(){
        if (instance==null){
            instance=new JsonParse();
        }
        return instance;
    }
    private String read(InputStream inputStream){
        BufferedReader reader=null;
        StringBuffer stringBuffer=null;
        String line=null;
        try{
            stringBuffer=new StringBuffer();
            reader=new BufferedReader(new InputStreamReader(inputStream));
            while ((line=reader.readLine())!=null){
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
        }catch (IOException e){
            e.printStackTrace();
            stringBuffer.append("\n");
        }finally {
            try {
                if (inputStream!=null)inputStream.close();
                if (reader!=null)reader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }
    public List<WeatherInfo> getInfosFormJson(Context context){
        List<WeatherInfo> weatherInfos=new ArrayList<>();
        InputStream inputStream=null;
        try {
            inputStream=context.getResources().getAssets().open("weather.json");
            String json=read(inputStream);
            Gson gson=new Gson();
            Type listType=new TypeToken<List<WeatherInfo>>(){}.getType();
            List<WeatherInfo> infoList=gson.fromJson(json,listType);
            return infoList;
        }catch (Exception e){}
        return weatherInfos;
    }
}
